---@class UGCPlayerController_C:BP_UGCPlayerController_C
--Edit Below--
local UGCPlayerController = {
    TopCamera = nil;
    LastTouchLocation = {
        x = 0,
        y = 0,
    };
    -- 第一根手指是否是第一次触摸
    FirstTouchOne = true;
    -- 第二根手指是否是第一次触摸
    FirstTouchTwo = true;
    -- 上次两指距离
    LastTwoFingerDistance = 0;
    -- 顶部摄像机缩放灵敏度(暂时不考虑镜头缩放)
    TopCameraScaleSensitive = 3;
    -- 顶部摄像机移动灵敏度
    TopCameraMoveSensitive = 3;
    -- 是否开启手指控制顶部摄像机移动 全局控制
    EnableCameraMove = false;
    -- 摄像机是否可以移动
    CameraCanMove = false;
    -- 是否可以前后左右拖动 边界控制
    CanMoveForward = true;
    CanMoveBack = true;
    CanMoveLeft = true;
    CanMoveRight = true;
    -- [CS]当前摄像机状态 默认位全局相机(默认最高位置)
    CurrentCameraState = 3;
    CurrentCameraHeight = 3;

    -- [S]每种摄像机状态时间
    CameraStateTimeMap = {
        FreeCameraTime = 0,
        AutoCameraTime = 0,
        GlobalCameraTime = 0
    };
    --每种高度持续时间
    CameraHeightTimeMap = {
        highTime = 0;
        midTime = 0;
        lowTime = 0;
    }
};

--注册Server RPC
function UGCPlayerController:GetAvailableServerRPCs()
    return
    "ServerRPC_ShowSelectCardTips",
    "ServerRPC_SelectCard",
    --"ClientRPC_SelectCardAgain",
    "ServerRPC_ShowRemainTimeTips",
    "ServerRPC_ReadyoMove"
end

function UGCPlayerController:ReceiveBeginPlay()
    ugcprint("UGCPlayerController:ReceiveBeginPlay")
    self.bNeedResetCameraOnPossess = false;
    if self:HasAuthority() == true then 
        self.PrimaryActorTick.bCanEverTick = true;
        self.bAllowBPReceiveTickEvent = true;
        self.bAllowReceiveTickEventOnDedicatedServer = true
        -- 断线重连事件(包括静默重连和杀进程重连)（切后台、断网重连、杀进程重连都会有回调）
        self.PlayerControllerReconnectedDelegate:Add(self.PlayerControllerReconnected, self);
        self.PlayerControllerRecoveredDelegate:Add(self.PlayerControllerRecovered, self);
    else
        Mode.OwnerController = self
        Mode.OwnerPlayerKey = Mode.OwnerController.PlayerKey;

        -- 加入队伍语音房间
        UGCVoiceManagerSystem.JoinVoiceRoom("AeroplaneVoiceRoomID")
        self:ActivateTouchInterface(nil)
        self.bAutoManageActiveCameraTarget = false;
        local CameraActors = GameplayStatics.GetAllActorsWithTag(self, "TopCamera")
        ugcprint("UGCPlayerController CameraActors num is:" .. #CameraActors)
        self.TopCamera = CameraActors[1];
        self.OnFingerMove:Add(self.OnTouchMove,self);
        self.OnReleaseScreen:Add(self.OnReleaseScreenCallBack,self);
        -- 将摄像机移到顶部
        self:SetCameraToTop(0);
        -- 监听棋子移动事件
        UGCEventSystem:AddListener(EventType.PlayerFlyPlane, self.OnPlayerFlyPlane, self);
        -- 断线重连事件(包括静默重连和杀进程重连)（仅在断线重连会有回调）
        -- self.OnReconnected:Add(self.OnClientReconnected, self);
    end
end

--[[
function UGCPlayerController:ServerRPC_SetChessAvatar()
    if self:HasAuthority() == false then return end
    local PlayerAvatarData = 
    {
        Gender = self.DefaultCharacterGender;
        PlayerName = self.PlayerName;
        AvatarItemIDList = {};
    }
    for _, ItemData in pairs(self.InitialItemList) do
        local ItemType = UGCItemSystem.GetItemType(ItemData.ItemTableID)
        local ItemSubType = UGCItemSystem.GetItemSubType(ItemData.ItemTableID)

        -- 4 类型为 Avatar
        -- 701 SubType为降落伞，需要过滤
        if ItemType == 4 and ItemSubType ~= 701 and ItemSubType ~= 411 then
            table.insert(PlayerAvatarData.AvatarItemIDList, ItemData.ItemTableID)
        end
    end

    for PlaneIndex, Plane in pairs(UGCGameSystem.GameState.PlayerInfos[self.PlayerState.TeamIndex].PlaneInfos) do
        Plane:SetAvatar(PlayerAvatarData)
    end
end
]]--

function UGCPlayerController:ReceiveEndPlay()
    ugcprint("UGCPlayerController : ReceiveEndPlay")

    UGCEventSystem:RemoveListener(EventType.PlayerFlyPlane, self.OnPlayerFlyPlane, self);
end

function UGCPlayerController:OnPlayerFlyPlane(TeamIndex, PlaneIndex, NumSteps)
    self:FocusCameraToPawn(TeamIndex, PlaneIndex)
end

-- 客户端玩家视角聚焦Pawn
function UGCPlayerController:FocusCameraToPawn(TeamIndex, PlaneIndex)
    ugcprint("UGCPlayerController:FocusCameraToPawn TeamIndex is" .. TeamIndex .. ",PlaneIndex is :" .. PlaneIndex);
    if self.CurrentCameraState ~= ECameraState.AutoCamera then
        return;
    end
    local Pawn = UGCGameSystem.GameState.PlayerInfos[TeamIndex].PlaneInfos[PlaneIndex];
    if Pawn ~= nil then
        self:SetCameraToPawn(Pawn)
    else
        print("UGCPlayerController:FocusCameraToPawn Pawn is nil");
    end
end

--[[摄像机相关]]--

--改高度
function UGCPlayerController:ReceiveTick(DeltaTime)
    if self:HasAuthority() == true then 
        if self.CurrentCameraHeight == ECameraHeight.high then
            self.CameraHeightTimeMap.highTime = self.CameraHeightTimeMap.highTime + DeltaTime;
        elseif self.CurrentCameraState == ECameraHeight.mid then
            self.CameraHeightTimeMap.midTime = self.CameraHeightTimeMap.midTime + DeltaTime;
        elseif self.CurrentCameraState == ECameraHeight.low then
            self.CameraHeightTimeMap.lowTime = self.CameraHeightTimeMap.lowTime + DeltaTime;
        end
    end
end
-- [C]设置摄像机高度,在AC_Main_UI里使用，（复制下面的
function UGCPlayerController:SetCameraHeight(NewHeight)
    
    if NewHeight > self.CurrentCameraHeight then
        --local Sweep = self.TopCamera.SceneComponent:K2_SetWorldLocation(HighLocation, false,nil, false);
        local moveOffset = {}
        moveOffset.x = 0;
        moveOffset.y = 300;
        moveOffset.z = 1000;
        local Sweep = self.TopCamera.SceneComponent:K2_AddWorldOffset(moveOffset, false,nil, false);
    elseif NewHeight < self.CurrentCameraHeight then
        local moveOffset = {}
        moveOffset.x = 0;
        moveOffset.y = -300;
        moveOffset.z = -1000;
        local Sweep = self.TopCamera.SceneComponent:K2_AddWorldOffset(moveOffset, false,nil, false);
    end
    self.CurrentCameraHeight = NewHeight;
    --将摄像头状态传给服务器
    UnrealNetwork.CallUnrealRPC(self, self, "ServerRPC_SetServerCameraHeight", NewHeight);
end
-- [C]设置摄像机状态,在AC_Main_UI里使用
function UGCPlayerController:SetCameraState(NewState)
    self.CurrentCameraState = NewState;
    --将摄像头状态传给服务器
    UnrealNetwork.CallUnrealRPC(self, self, "ServerRPC_SetServerCameraState", NewState);
end
--标注使用时间
function UGCPlayerController:TlogCameraStateUseTime()
    for i, v in pairs(self.CameraStateTimeMap) do
        print("UGCPlayerController:TlogCameraStateUseTime Key:" .. tostring(self.PlayerState.TeamIndex) .. "_" .. tostring(i) .. ",Value is:" .. tostring(math.floor(v)));
        NetUtil.SendPacketCustom(tostring(self.PlayerState.TeamIndex) .. "_" .. tostring(i), tostring(math.floor(v)));
    end
end
--结束
function UGCPlayerController:ReceiveEndPlay()
    ugcprint("UGCPlayerController : ReceiveEndPlay")
    --UGCEventSystem:RemoveListener(AeroplaneChessEventType.PlayerFlyPlane, self.OnPlayerFlyPlane, self);
end
-- [C]设置摄像机到顶部(！！用于把摄像头从角色身上移开！！这个很关键)
function UGCPlayerController:SetCameraToTop(blendTime) 
    if self.TopCamera == nil then
        print("UGCPlayerController:SetCameraToTop SetCameraToTop but topCamera is nil")
    end
    self:SetViewTargetWithBlend(self.TopCamera,blendTime,EViewTargetBlendFunction.VTBlend_Linear,0, false); 
    ugcprint("UGCPlayerController:SetCameraToTop SetViewTargetWithBlend end");
    self.EnableCameraMove = true;
end
-- 重置摄像机位置
function UGCPlayerController:ResetCameraLocation()
    if self.TopCamera ~= nil then
        if self.TopCamera.CameraOriLocation ~= nil then
            self.TopCamera:K2_SetActorLocation(self.TopCamera.CameraOriLocation);
        end
    end
end
-- 拖动判定逻辑
function UGCPlayerController:OnTouchMove(FingerIndex, Location)
    if self.EnableCameraMove ~= true then
        print("UGCPlayerController:OnTouchMove EnableCameraMove is false");
        return;
    end
    ugcprint("UGCPlayerController:OnTouchMove:" .. FingerIndex)
    -- 只有一指 进行移动逻辑
    if FingerIndex == 0 and self.FirstTouchOne then
        self.CameraCanMove = true;
        self.CameraCanScale = false;
    end
    -- 两指同时，进入缩放逻辑
    if FingerIndex == 1 and self.FirstTouchTwo then
        self.CameraCanMove = false;
        self.CameraCanScale = true;
    end
    
    if self.CameraCanMove and self.CurrentCameraState ~= ECameraState.AutoCamera then
        if FingerIndex == 0 and self.FirstTouchOne then
        self.LastTouchLocation.x = Location.x;
        self.LastTouchLocation.y = Location.y;
            self.FirstTouchOne = false;
            ugcprint("UGCPlayerController:OnTouchMove FingerOne first touch")
        return;
        elseif FingerIndex == 0 and not self.FirstTouchOne then
        local ScreenOffset = {}
        -- 注意ScrrenOffset的Y变化对应的摄像机前后移动 X变化对应的左右移动
        ScreenOffset.x = -(Location.x - self.LastTouchLocation.x);
        ScreenOffset.y = (Location.y - self.LastTouchLocation.y);
        self:LimitScreenOffset(ScreenOffset)
        if self.TopCamera ~= nil then
            -- 因为是俯视角 所以前后方向拿到摄像机的UpVector,对应UE4 Z轴
            local ForwardVector = VectorHelper.ToLuaTable(self.TopCamera.SceneComponent:GetUpVector());
            -- forwardVector表示摄像机前后移动的方向，值为UpVector的去除掉Z轴分量的值然后标准化
            ForwardVector.z = 0;
            ForwardVector = KismetMathLibrary.Normal(ForwardVector);
            ForwardVector.x = ForwardVector.x * ScreenOffset.y * self.TopCameraMoveSensitive;
            ForwardVector.y = ForwardVector.y * ScreenOffset.y * self.TopCameraMoveSensitive;
            -- 左右方向拿到摄像机的RightVector,对应UE4 Y轴
            local RightVector = self.TopCamera.SceneComponent:GetRightVector()
            -- RightVector表示摄像机左右移动的方向，值为RightVector的去除掉Z轴分量的值然后标准化
            RightVector.z = 0;
            RightVector = KismetMathLibrary.Normal(RightVector);
            RightVector.x = RightVector.x * ScreenOffset.x * self.TopCameraMoveSensitive;
            RightVector.y = RightVector.y * ScreenOffset.x * self.TopCameraMoveSensitive;
            -- 最终的移动向量
            local moveOffset = {}
            moveOffset.x = ForwardVector.x + RightVector.x
            moveOffset.y = ForwardVector.y + RightVector.y
            local Sweep = self.TopCamera.SceneComponent:K2_AddWorldOffset(moveOffset, false,nil, false);
        end
        self.LastTouchLocation.x = Location.x;
        self.LastTouchLocation.y = Location.y;
    end
    elseif self.CameraCanScale and self.CurrentCameraState == ECameraState.FreeCamera then
        if FingerIndex == 1 and self.FirstTouchTwo then
            local IsTwoFinger,Distance = self:GetTwoFingerDistance();
            if IsTwoFinger then
                self.LastTwoFingerDistance = Distance;
            else
                print("UGCPlayerController:OnTouchMove CameraCanScale is True,But dont find two Finger Pressed");
            end
            self.FirstTouchTwo = false;
            return;
        elseif FingerIndex == 1 and not self.FirstTouchTwo then
            local IsTwoFinger,Distance = self:GetTwoFingerDistance();
            if IsTwoFinger then
                local ScaleValue = Distance - self.LastTwoFingerDistance;
                -- 摄像机缩放
                self.TopCamera:ScaleCamera(ScaleValue * self.TopCameraScaleSensitive);
                self.LastTwoFingerDistance = Distance;
            else
                print("UGCPlayerController:OnTouchMove self.FirstTouchTwo is false and CameraCanScale is True,But dont find two Finger Pressed");
            end
        end
    end
end
-- 获得两指距离
function UGCPlayerController:GetTwoFingerDistance()
    local LocationX_Finger1,LocationY_Finger1,IsPressed_Finger1 = self:GetInputTouchState(ETouchIndex.Touch1);
    local LocationX_Finger2,LocationY_Finger2,IsPressed_Finger2 = self:GetInputTouchState(ETouchIndex.Touch2);
    local Location_Finger1 = {X = LocationX_Finger1,Y = LocationY_Finger1};
    local Location_Finger2 = {X = LocationX_Finger2,Y = LocationY_Finger2};
    local Distance = VectorHelper.GetDistance2D(Location_Finger1,Location_Finger2);
    return IsPressed_Finger1 and IsPressed_Finger2,Distance
end
-- 根据是否到达地图边界限制MoveOffset的拖动
function UGCPlayerController:LimitScreenOffset(moveOffset)
    if self.CanMoveForward == false then
        if moveOffset.y > 0 then
            moveOffset.y = 0
        end
    end
    if self.CanMoveBack == false then
        if moveOffset.y < 0 then
            moveOffset.y = 0
        end
    end
    if self.CanMoveRight == false then
        if moveOffset.x > 0 then
            moveOffset.x = 0
        end
    end
    if self.CanMoveLeft == false then
        if moveOffset.x < 0 then
            moveOffset.x = 0
        end
    end
end
-- 当手指离开屏幕
function UGCPlayerController:OnReleaseScreenCallBack(FingerIndex)
    if self.EnableCameraMove ~= true then
        print("UGCPlayerController:OnReleaseScreenCallBack is false");
        return;
    end
    ugcprint("UGCPlayerController:OnReleaseScreenCallBack");
    if FingerIndex == 0 then
        self.FirstTouchOne = true
    elseif FingerIndex == 1 then
        self.FirstTouchTwo = true
    end
end
-- 切换视角到棋子上(不需要)
function UGCPlayerController:SetCameraToPawn(Pawn)
    self:SetViewTargetWithBlend(Pawn,0.5,EViewTargetBlendFunction.VTBlend_Linear,0, false); 
end

--[[------------------------------------------ServerRPC------------------------------------------------------]]--

-- 请求选择卡牌，客户端->服务端
function UGCPlayerController:ServerRPC_SelectCard(CardInfo)
    if self:HasAuthority() == false then return end
    if UGCGameSystem.GameState:GetCurRoundPlayerInfo().PlayerKey ~= self.PlayerKey then
        print("UGCPlayerController:ServerRPC_SelectCard Not Current Player!");
        return
    end
    UGCGameSystem.GameState:SelectCard(CardInfo)
end

-- 请求关闭选择卡牌提示
function UGCPlayerController:ServerRPC_ShowSelectCardTips(open)
    if self:HasAuthority() == false then return end
    UnrealNetwork.CallUnrealRPC_Multicast(UGCGameSystem.GameState, "Multicast_ShowSelectCardTips", open);
end

-- 请求关闭剩余时间提示
function UGCPlayerController:ServerRPC_ShowRemainTimeTips(open)
    if self:HasAuthority() == false then return end
    ugcprint("UGCPlayerController:ServerRPC_ShowRemainTimeTips "..tostring(open));
    UnrealNetwork.CallUnrealRPC_Multicast(UGCGameSystem.GameState, "Multicast_ShowRemainTimeTips", open);
end

-- 设置服务器记录当前摄像机状态
function UGCPlayerController:ServerRPC_SetServerCameraState(NewCameraState)
    self.CurrentCameraState = NewCameraState;
end

-- 设置服务器记录当前摄像机高度（复制上面的
function UGCPlayerController:ServerRPC_SetServerCameraHeight(NewCameraHeight)
    self.CurrentCameraHeight = NewCameraHeight;
end

-- 请求移动棋子，客户端->服务端
function UGCPlayerController:ServerRPC_ReadyoMove(direection,targetTile)
    if self:HasAuthority() == false then return end
    ugcprint("UGCPlayerController:ServerRPC_ReadyoMove");
    if UGCGameSystem.GameState:GetCurRoundPlayerInfo().PlayerKey ~= self.PlayerKey then
        print("UGCPlayerController:ServerRPC_ReadyoMove Not Current Player!");
        return
    end
    UGCGameSystem.GameState:DoMovePlayer(direection,targetTile)
    
end




--[[------------------------------------------ClientRPC------------------------------------------------------]]--

-- 通知客户端展示选择卡牌按钮
function UGCPlayerController:ClientRPC_StartCardSelection(CardInfos)
    --log_tree_dev("UGCPlayerController:ClientRPC_StartPlaneSelection", CanChoosePlaneIndex)
    if UIManager then
        UIManager.MainUI:ShowCardSelectionPanel(true);
    end
end

-- 通知客户端开启当前回合选择卡牌提示，注意是提示
function UGCPlayerController:ClientRPC_ShowSelectCardTips(IsShow)
    self.ShowSelectCardTips = IsShow;
end

-- 客户端玩家回到顶部
function UGCPlayerController:ClientRPC_FocusCameraToTop()
    ugcprint("UGCPlayerController:ClientRPC_FocusCameraToTop");
    self:SetCameraToTop(1)
end

-- 通知客户端再次选择卡牌
function UGCPlayerController:ClientRPC_SelectCardAgain(AtHomeNum, IsSix)
    ugcprint("UGCPlayerController:ClientRPC_ShowCanFly:  "..tostring(AtHomeNum));
    ugcprint("UGCPlayerController:ClientRPC_ShowCanFly:  "..tostring(IsSix));
    if UIManager then
        UIManager.MainUI.AC_56Tips:Show(AtHomeNum, IsSix);
    end
end



return UGCPlayerController;